package com.ignou.mca.evote;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ignou.mca.datasource.DataBaseUtilities;
import com.ignou.mca.datasource.Encryption;
import com.ignou.mca.beans.Message;
import com.ignou.mca.beans.VotersFormBean;
import com.ignou.mca.util.RandamNumberGeneration;
import com.ignou.mca.util.SessionUtil;
import org.apache.log4j.Logger;

//AddUsers used to add users(voters)
public class AddUsers extends HttpServlet implements Servlet {
	
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String firstName = req.getParameter("firstName");
		String lastName = req.getParameter("lastName");
		String age = req.getParameter("Age");
		String sex = req.getParameter("Sex");
		String address1 = req.getParameter("address1");
		String address2 = req.getParameter("address2");
		String city = req.getParameter("city");
		String state = req.getParameter("state");
		String country = req.getParameter("country");
		String pinCode = req.getParameter("pinCode");
		String phoneNumber = req.getParameter("phoneNumber");
		String email = req.getParameter("email");
		String userName = req.getParameter("userName");
		//String role = req.getParameter("role");
		String password = req.getParameter("password");
		String repeatPassword = req.getParameter("repeatPassword");
		String securityQuestion = req.getParameter("securityQuestion");
		String securityAnswer = req.getParameter("securityAnswer");
		String activeStatus = "inactive";
		
		Message message = new Message();
		VotersFormBean voters = new VotersFormBean();
		voters.setFirstName(firstName);
		voters.setLastName(lastName);
		voters.setAge(age);
		voters.setSex(sex);
		voters.setAddress1(address1);
		voters.setAddress2(address2);
		voters.setCity(city);
		voters.setState(state);
		voters.setCountry(country);
		voters.setPinCode(pinCode);
		voters.setPhonenumber(phoneNumber);
		voters.setEmail(email);
		voters.setUserName(userName);
		//voters.setRole(role);
		voters.setPassword(password);
		voters.setRepeatPassword(repeatPassword);
		voters.setSecurityQuestion(securityQuestion);
		voters.setSecurityAnswer(securityAnswer);
		voters.setActiveStatus(activeStatus);
		
		
		HttpSession session = req.getSession(true);
		session.setAttribute("Message", message);
		req.setAttribute("Voters", voters);
		ServletContext context = getServletContext();

		if(!SessionUtil.validateSession(req,resp)){
			resp.sendRedirect(req.getServletPath()+"/Login.jsp");
			return;
		}
		DataBaseUtilities dbu = new DataBaseUtilities();
		if (!password.equals(repeatPassword)) {
			message.setMessage("The Passwords you have entered not equal.Please check and try again");
			context.getRequestDispatcher("/AddVoters.jsp").forward(req, resp);
		} else if ((firstName.equalsIgnoreCase(""))
				|| (lastName.equalsIgnoreCase(""))
				|| (address1.equalsIgnoreCase(""))
				|| (city.equalsIgnoreCase(""))
				|| (state.equalsIgnoreCase(""))
				|| (country.equalsIgnoreCase(""))
				|| (email.equalsIgnoreCase(""))
				|| (pinCode.equalsIgnoreCase(""))
				|| (phoneNumber.equalsIgnoreCase(""))
				|| (userName.equalsIgnoreCase(""))
				|| (password.equalsIgnoreCase(""))
				|| (securityQuestion.equalsIgnoreCase(""))
				|| (repeatPassword.equalsIgnoreCase(""))
				|| (securityAnswer.equalsIgnoreCase(""))) {
			message.setMessage("You have not completed all the fields.Please complete all mandatory fields.");
			context.getRequestDispatcher("/AddVoters.jsp").forward(req, resp);
		} else if (dbu.checkUsername(userName,email)) {
			message.setMessage("The username already exists or email already registered. Please select another one.");
			req.setAttribute("ErrorMessage","The username already exists or email already registered. Please select another one.");
			context.getRequestDispatcher("/TransactionFailed.jsp").forward(req, resp);
		} else {
			/*try {
				password = Encryption.encrypt(password);
			} catch (Exception e) {
				e.printStackTrace();
			}*/

			Calendar cal = Calendar.getInstance();
			Date dd = new Date(cal.getTimeInMillis());
			
			Connection con = dbu.getConnection();
			String random=RandamNumberGeneration.rand(350,500)+RandamNumberGeneration.randomstring(3,10)+RandamNumberGeneration.rand(550,700);
			
			String query = "insert into users(FirstName,LastName,Address1," +
					"Address2,city,state,country,phone,email,username,password,securityQuestion,securityAnswer," +
					"role,activeStatus,RandomNumber,activationDate) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			
			try {
				PreparedStatement pst = con.prepareStatement(query);
				pst.setString(1, voters.getFirstName());
				pst.setString(2, voters.getLastName());
				pst.setString(3, voters.getAddress1());
				pst.setString(4, voters.getAddress2());
				pst.setString(5, voters.getCity());
				pst.setString(6, voters.getState());
				pst.setString(7, voters.getCountry());
				pst.setString(8, voters.getPhonenumber());
				pst.setString(9, voters.getEmail());
				pst.setString(10, voters.getUserName());
				pst.setString(11, password);
				pst.setString(12, voters.getSecurityQuestion());
				pst.setString(13, voters.getSecurityAnswer());
				pst.setString(14, "User");
				pst.setString(15, "Active");
				pst.setString(16, random);
				pst.setDate(17,dd);

				int i = pst.executeUpdate();
					
				if(i==1)
				{
					SessionUtil.sendMail(voters.getEmail(), voters.getUserName(), voters.getPassword(), "register",random);
					context.getRequestDispatcher("/AdminMenu.jsp").forward(req,resp);
					con.close();
				}else
				{
					context.getRequestDispatcher("/TransactionFailed.jsp").forward(req,resp);
				}
				
			}catch(Exception e)
			{
				try {
					con.close();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
//			Boolean userSuccess = dbu.addUser(voters);
//			if(userSuccess)
//			{
//				context.getRequestDispatcher("/AdminMenu.jsp").forward(req,
//						resp);
//			}else
//			{
//				context.getRequestDispatcher("/TransactionFailed.jsp").forward(req,
//						resp);
//			}
			
		}
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	}
}